<?php

namespace App\Services;

use App\Models\Channel;
use App\Models\ChannelLog;
use Carbon\Carbon;

class ChannelService extends BaseService
{

    public function record($type, $time, $appid)
    {
        if (!in_array($type, [1, 2])) {
            $this->errMsg = '时间类型非法';
            return false;
        }
        if (!$appid) {
            $this->errMsg = 'appid异常';
            return false;
        }

        $channel = Channel::where('appid', $appid)->first();
        if (!$channel) {
            $this->errMsg = '数据提交失败';
            return false;
        }

        if ($type == 1) {

            $channelLog = ChannelLog::where('channel_id', $channel->id)->orderByDesc('id')->first();

            $index = ($channelLog) ? $channelLog->index + 1 : 1;
            $res = ChannelLog::create([
                'channel_id'    =>  $channel->id,
                'start_time'    =>  Carbon::now()->setTimezone('Asia/Shanghai'),
                'index' =>  $index
            ]);

            if ($res) {
                return true;
            }

            $this->errMsg = '操作异常';
            return false;
        }

        // type == 2
        $channelLog = ChannelLog::where('channel_id', $channel->id)
            ->whereNotNull('start_time')
            ->whereNull('end_time')
            ->orderByDesc('id')
            ->first();
        if (!$channelLog) {
            $this->errMsg = '记录异常';
            return false;
        }

        $channelLog->end_time = Carbon::now()->setTimezone('Asia/Shanghai');
        $channelLog->usage_seconds = Carbon::parse($channelLog->end_time)->diffInSeconds(Carbon::parse($channelLog->start_time)->setTimezone('Asia/Shanghai'));

        if ($channelLog->save()) {
            return true;
        }

        $this->errMsg = '操作异常';
        return false;
    }

    private function isValidTimestamp($timestamp) {
        // 检查是否是数字并且是正整数
        if (is_numeric($timestamp) && (int)$timestamp == $timestamp && $timestamp > 0) {
            // 使用 date() 和 strtotime() 检查是否可以转换为有效日期
            $date = date('Y-m-d H:i:s', $timestamp);
            return strtotime($date) === (int)$timestamp;
        }
        return false;
    }
}
